/**
 * 聊天消息管理器 - 简化消息同步逻辑
 * 解决临时消息匹配和重复消息问题
 */
import appStateManager from './app-state-manager.js'

class ChatMessageManager {
  constructor() {
    this.messages = new Map() // roomId -> messages[]
    this.tempMessages = new Map() // tempId -> message
    this.callbacks = new Map() // roomId -> callbacks[]
    this.maxMessagesPerRoom = 200 // 每个房间最多保留200条消息
    this.cleanupThreshold = 250 // 超过250条时触发清理
    
    console.log('聊天消息管理器初始化完成')
  }

  // 生成房间ID（兼容旧版本格式）
  generateRoomId(userIds, roomType = 'private') {
    if (roomType === 'private') {
      // 私聊：保持与旧版本兼容的格式 pm_minId_maxId
      const sortedIds = userIds.map(id => parseInt(id)).sort((a, b) => a - b)
      return `pm_${sortedIds[0]}_${sortedIds[1]}`
    } else if (roomType === 'group') {
      // 群聊：使用时间戳和随机数
      return `group_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    }
    return `room_${Date.now()}`
  }

  // 订阅房间消息变化
  subscribe(roomId, callback) {
    if (!this.callbacks.has(roomId)) {
      this.callbacks.set(roomId, [])
    }
    this.callbacks.get(roomId).push(callback)
    
    // 立即返回当前消息列表
    const messages = this.getMessages(roomId)
    callback(messages)
    
    console.log(`订阅房间消息: ${roomId}, 当前订阅数: ${this.callbacks.get(roomId).length}`)
  }

  // 取消订阅
  unsubscribe(roomId, callback) {
    if (this.callbacks.has(roomId)) {
      const callbacks = this.callbacks.get(roomId)
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
        console.log(`取消订阅房间消息: ${roomId}`)
      }
    }
  }

  // 通知订阅者
  notifySubscribers(roomId) {
    if (this.callbacks.has(roomId)) {
      const callbacks = this.callbacks.get(roomId)
      const messages = this.getMessages(roomId)
      
      callbacks.forEach(callback => {
        try {
          callback(messages)
        } catch (error) {
          console.error(`消息回调执行失败 (${roomId}):`, error)
        }
      })
    }
  }

  // 发送消息（简化版）
  async sendMessage(roomId, content, messageType = 'text', chatService) {
    if (!content || !content.trim()) {
      throw new Error('消息内容不能为空')
    }

    const currentUser = this.getCurrentUser()
    if (!currentUser) {
      throw new Error('用户未登录')
    }

    // 生成临时消息ID
    const tempId = `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    const tempMessage = {
      tempId,
      roomId,
      content: content.trim(),
      type: messageType,
      timestamp: new Date().toISOString(),
      status: 'sending',
      sender: {
        id: currentUser.id,
        name: currentUser.name,
        avatar: currentUser.avatar
      }
    }

    // 立即显示临时消息
    this.addTempMessage(roomId, tempMessage)

    try {
      console.log(`发送消息到房间 ${roomId}:`, content)
      
      // 发送到服务器
      await chatService.sendMessage(content, roomId)
      
      // 更新临时消息状态为已发送
      this.updateTempMessage(tempId, { status: 'sent' })
      
      console.log('消息发送成功')
      
    } catch (error) {
      console.error('消息发送失败:', error)
      
      // 更新临时消息状态为失败
      this.updateTempMessage(tempId, { status: 'failed' })
      
      throw error
    }
  }

  // 添加临时消息
  addTempMessage(roomId, tempMessage) {
    // 保存临时消息引用
    this.tempMessages.set(tempMessage.tempId, tempMessage)
    
    // 添加到消息列表
    if (!this.messages.has(roomId)) {
      this.messages.set(roomId, [])
    }
    
    const messages = this.messages.get(roomId)
    messages.push(tempMessage)
    
    // 通知订阅者
    this.notifySubscribers(roomId)
    
    console.log(`添加临时消息: ${tempMessage.tempId}`)
  }

  // 更新临时消息状态
  updateTempMessage(tempId, updates) {
    if (this.tempMessages.has(tempId)) {
      const tempMessage = this.tempMessages.get(tempId)
      Object.assign(tempMessage, updates)
      
      // 通知对应房间的订阅者
      this.notifySubscribers(tempMessage.roomId)
      
      console.log(`更新临时消息状态: ${tempId}`, updates)
    }
  }

  // 处理服务器消息（增强版）
  handleServerMessage(message) {
    const roomId = message.roomId
    
    console.log(`收到服务器消息 (房间: ${roomId}):`, message)
    
    // 检查消息类型
    if (message.type === 'read_receipt') {
      // 处理已读回执
      this.handleReadReceipt(message)
      return
    }
    
    // 移除对应的临时消息
    this.removeTempMessagesByContent(roomId, message.content, message.sender.id)
    
    // 添加真实消息（带去重检查）
    this.addMessage(roomId, {
      id: message.id,
      roomId: message.roomId,
      content: message.content,
      type: message.type || 'text',
      timestamp: message.timestamp,
      status: 'delivered', // 初始状态为已送达但未读
      sender: message.sender
    })
    
    // 更新聊天列表中的未读消息计数
    this.updateChatListUnreadCount(message)
  }
  
  // 更新聊天列表中的未读消息计数
  updateChatListUnreadCount(message) {
    try {
      // 检查是否是自己发送的消息
      const currentUser = this.getCurrentUser()
      if (currentUser && message.sender.id == currentUser.id) {
        // 自己发送的消息不计入未读
        return
      }
      
      // 获取聊天列表
      const chatListStr = uni.getStorageSync('chat_list')
      if (!chatListStr) return
      
      const chatList = JSON.parse(chatListStr)
      if (!Array.isArray(chatList)) return
      
      // 查找对应的聊天
      const chat = chatList.find(c => c.id === message.roomId)
      if (chat) {
        // 更新未读消息计数
        chat.unreadCount = (chat.unreadCount || 0) + 1
        // 更新最后一条消息
        chat.lastMessage = message.content
        chat.lastMessageTime = message.timestamp
        
        // 保存更新后的聊天列表
        uni.setStorageSync('chat_list', JSON.stringify(chatList))
        console.log(`已更新聊天 ${message.roomId} 的未读消息计数:`, chat.unreadCount)
      } else {
        // 如果聊天不存在，创建新的聊天项
        const newChat = {
          id: message.roomId,
          name: message.sender.name,
          avatar: message.sender.avatar || '',
          lastMessage: message.content,
          lastMessageTime: message.timestamp,
          unreadCount: 1,
          isOnline: true,
          isPinned: false,
          isMuted: false
        }
        
        chatList.push(newChat)
        uni.setStorageSync('chat_list', JSON.stringify(chatList))
        console.log(`已添加新聊天 ${message.roomId}，未读消息计数: 1`)
      }
    } catch (error) {
      console.error('更新聊天列表未读消息计数失败:', error)
    }
  }
  
  // 处理已读回执
  handleReadReceipt(receipt) {
    if (!receipt.data || !receipt.data.message_ids || !receipt.roomId) {
      console.warn('收到无效的已读回执:', receipt)
      return
    }
    
    const roomId = receipt.roomId
    const messageIds = Array.isArray(receipt.data.message_ids) 
      ? receipt.data.message_ids 
      : [receipt.data.message_ids]
    
    if (!this.messages.has(roomId)) return
    
    const messages = this.messages.get(roomId)
    let hasChanges = false
    
    // 更新消息状态为已读
    messageIds.forEach(messageId => {
      const message = messages.find(m => m.id == messageId)
      if (message && message.status !== 'read') {
        message.status = 'read'
        hasChanges = true
        console.log(`消息已标记为已读: ${messageId}`)
      }
    })
    
    // 如果有更改，通知订阅者
    if (hasChanges) {
      this.notifySubscribers(roomId)
    }
  }

  // 移除临时消息（通过内容和发送者匹配）
  removeTempMessagesByContent(roomId, content, senderId) {
    if (!this.messages.has(roomId)) return
    
    const messages = this.messages.get(roomId)
    const initialLength = messages.length
    
    // 移除匹配的临时消息
    for (let i = messages.length - 1; i >= 0; i--) {
      const msg = messages[i]
      if (msg.tempId && 
          msg.content === content && 
          msg.sender.id == senderId &&
          (msg.status === 'sending' || msg.status === 'sent')) {
        
        // 从临时消息Map中移除
        this.tempMessages.delete(msg.tempId)
        
        // 从消息列表中移除
        messages.splice(i, 1)
        
        console.log(`移除临时消息: ${msg.tempId}`)
        break // 只移除第一个匹配的
      }
    }
    
    // 如果有移除操作，通知订阅者
    if (messages.length !== initialLength) {
      this.notifySubscribers(roomId)
    }
  }

  // 添加消息（带去重）
  addMessage(roomId, message) {
    if (!this.messages.has(roomId)) {
      this.messages.set(roomId, [])
    }
    
    const messages = this.messages.get(roomId)
    
    // 简化的去重逻辑
    const isDuplicate = messages.some(existingMsg => {
      // 检查ID相同
      if (message.id && existingMsg.id === message.id) {
        return true
      }
      
      // 检查内容、时间戳和发送者相同（容忍1秒时间差）
      if (existingMsg.content === message.content &&
          existingMsg.sender.id == message.sender.id) {
        const timeDiff = Math.abs(
          new Date(existingMsg.timestamp) - new Date(message.timestamp)
        )
        return timeDiff < 1000 // 1秒内认为是重复消息
      }
      
      return false
    })
    
    if (!isDuplicate) {
      messages.push(message)
      
      // 触发清理检查
      this.checkAndCleanupMessages(roomId)
      
      // 通知订阅者
      this.notifySubscribers(roomId)
      
      console.log(`添加新消息到房间 ${roomId}: ${message.content}`)
    } else {
      console.log(`跳过重复消息: ${message.content}`)
    }
  }

  // 检查并清理旧消息
  checkAndCleanupMessages(roomId) {
    if (!this.messages.has(roomId)) return
    
    const messages = this.messages.get(roomId)
    
    if (messages.length > this.cleanupThreshold) {
      // 保留最新的消息
      const keepCount = this.maxMessagesPerRoom
      const removedCount = messages.length - keepCount
      
      messages.splice(0, removedCount)
      
      console.log(`清理房间 ${roomId} 的旧消息，移除 ${removedCount} 条`)
    }
  }

  // 获取房间消息
  getMessages(roomId) {
    if (!this.messages.has(roomId)) {
      return []
    }
    
    // 返回按时间排序的消息副本
    const messages = [...this.messages.get(roomId)]
    return messages.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
  }

  // 设置历史消息
  setHistoryMessages(roomId, historyMessages) {
    if (!Array.isArray(historyMessages)) {
      console.error('历史消息必须是数组')
      return
    }
    
    // 清除现有消息
    this.messages.set(roomId, [])
    
    // 添加历史消息
    historyMessages.forEach(msg => {
      this.addMessage(roomId, {
        id: msg.id,
        roomId: roomId,
        content: msg.content,
        type: msg.message_type || msg.type || 'text',
        timestamp: msg.timestamp,
        status: 'delivered',
        sender: {
          id: msg.user_id || msg.sender?.id,
          name: msg.user_name || msg.sender?.name,
          avatar: msg.sender?.avatar || ''
        }
      })
    })
    
    console.log(`设置房间 ${roomId} 历史消息: ${historyMessages.length} 条`)
  }

  // 清空房间消息
  clearRoomMessages(roomId) {
    this.messages.delete(roomId)
    
    // 清理相关的临时消息
    for (const [tempId, tempMsg] of this.tempMessages.entries()) {
      if (tempMsg.roomId === roomId) {
        this.tempMessages.delete(tempId)
      }
    }
    
    this.notifySubscribers(roomId)
    console.log(`清空房间 ${roomId} 的所有消息`)
  }

  // 获取当前用户
  getCurrentUser() {
    try {
      const currentUser = uni.getStorageSync('currentUser')
      if (currentUser) {
        return JSON.parse(currentUser)
      }
    } catch (error) {
      console.error('获取当前用户失败:', error)
    }
    return null
  }

  // 获取房间统计信息
  getRoomStats(roomId) {
    const messages = this.getMessages(roomId)
    const tempCount = Array.from(this.tempMessages.values())
      .filter(msg => msg.roomId === roomId).length
    
    return {
      totalMessages: messages.length,
      tempMessages: tempCount,
      lastMessage: messages.length > 0 ? messages[messages.length - 1] : null
    }
  }

  // 销毁管理器
  destroy() {
    this.messages.clear()
    this.tempMessages.clear()
    this.callbacks.clear()
    console.log('聊天消息管理器已销毁')
  }
}

// 创建全局单例
const chatMessageManager = new ChatMessageManager()

// 导出单例
export default chatMessageManager 